﻿// Decompiled with JetBrains decompiler
// Type: MCM.Internal.MCMImplementationSubModule
// Assembly: MCMv5, Version=5.10.2.0, Culture=neutral, PublicKeyToken=null
// MVID: 7AB326B9-B2B4-41C2-9177-68E944071101
// Assembly location: D:\steam\steamapps\workshop\content\261550\2859238197\bin\Win64_Shipping_Client\MCMv5.dll

using BUTR.DependencyInjection;
using MCM.Abstractions.GameFeatures;
using MCM.Abstractions.Properties;
using MCM.Implementation;
using MCM.Implementation.FluentBuilder;
using MCM.Implementation.Global;
using MCM.Implementation.PerCampaign;
using MCM.Implementation.PerSave;
using MCM.Internal.Extensions;
using MCM.Internal.GameFeatures;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using TaleWorlds.CampaignSystem;
using TaleWorlds.Core;
using TaleWorlds.Engine;
using TaleWorlds.MountAndBlade;

#nullable enable
namespace MCM.Internal
{
  internal class MCMImplementationSubModule : MBSubModuleBase, IGameEventListener
  {
    public event Action? GameStarted;

    public event Action? GameLoaded;

    public event Action? GameEnded;

    private bool ServiceRegistrationWasCalled { get; set; }

    public void OnServiceRegistration()
    {
      this.ServiceRegistrationWasCalled = true;
      IGenericServiceContainer serviceContainer = this.GetServiceContainer();
      if (serviceContainer == null)
        return;
      serviceContainer.AddSettingsContainer<FluentGlobalSettingsContainer>();
      serviceContainer.AddSettingsContainer<ExternalGlobalSettingsContainer>();
      serviceContainer.AddSettingsContainer<GlobalSettingsContainer>();
      serviceContainer.AddSettingsContainer<FluentPerSaveSettingsContainer>();
      serviceContainer.AddSettingsContainer<PerSaveSettingsContainer>();
      serviceContainer.AddSettingsContainer<FluentPerCampaignSettingsContainer>();
      serviceContainer.AddSettingsContainer<PerCampaignSettingsContainer>();
      serviceContainer.AddSettingsFormat<JsonSettingsFormat>();
      serviceContainer.AddSettingsFormat<XmlSettingsFormat>();
      serviceContainer.AddSettingsPropertyDiscoverer<IAttributeSettingsPropertyDiscoverer, AttributeSettingsPropertyDiscoverer>();
      serviceContainer.AddSettingsPropertyDiscoverer<IFluentSettingsPropertyDiscoverer, FluentSettingsPropertyDiscoverer>();
      serviceContainer.AddSettingsBuilderFactory<DefaultSettingsBuilderFactory>();
      serviceContainer.AddSettingsProvider<DefaultSettingsProvider>();
      serviceContainer.AddSingleton<IGameEventListener, MCMImplementationSubModule>((Func<IGenericServiceFactory, IGameEventListener>) (sp => (IGameEventListener) this));
      serviceContainer.AddSingleton<ICampaignIdProvider, CampaignIdProvider>();
      serviceContainer.AddSingleton<IFileSystemProvider, FileSystemProvider>();
      serviceContainer.AddScoped<PerSaveCampaignBehavior>();
      serviceContainer.AddTransient<IPerSaveSettingsProvider, PerSaveCampaignBehavior>((Func<IGenericServiceFactory, IPerSaveSettingsProvider>) (sp => (IPerSaveSettingsProvider) sp.GetService<PerSaveCampaignBehavior>()));
    }

    protected override void OnSubModuleLoad()
    {
      base.OnSubModuleLoad();
      MCMImplementationSubModule.PerformMigration001();
      MCMImplementationSubModule.PerformMigration002();
      if (this.ServiceRegistrationWasCalled)
        return;
      this.OnServiceRegistration();
    }

    protected override void OnBeforeInitialModuleScreenSetAsRoot()
    {
      base.OnBeforeInitialModuleScreenSetAsRoot();
    }

    protected override void OnGameStart(Game game, IGameStarter gameStarterObject)
    {
      base.OnGameStart(game, gameStarterObject);
      if (!(game.GameType is Campaign))
        return;
      Action gameStarted = this.GameStarted;
      if (gameStarted != null)
        gameStarted();
      ((CampaignGameStarter) gameStarterObject).AddBehavior((CampaignBehaviorBase) GenericServiceProvider.GetService<PerSaveCampaignBehavior>());
    }

    public override void OnNewGameCreated(Game game, object initializerObject)
    {
      base.OnNewGameCreated(game, initializerObject);
      if (!(game.GameType is Campaign))
        return;
      Action gameLoaded = this.GameLoaded;
      if (gameLoaded != null)
        gameLoaded();
    }

    public override void OnGameLoaded(Game game, object initializerObject)
    {
      base.OnGameLoaded(game, initializerObject);
      if (!(game.GameType is Campaign))
        return;
      Action gameLoaded = this.GameLoaded;
      if (gameLoaded != null)
        gameLoaded();
    }

    public override void OnGameEnd(Game game)
    {
      base.OnGameEnd(game);
      if (!(game.GameType is Campaign))
        return;
      Action gameEnded = this.GameEnded;
      if (gameEnded != null)
        gameEnded();
    }

    private static void PerformMigration001()
    {
      try
      {
        string fullPath = System.IO.Path.GetFullPath("Configs");
        string path = System.IO.Path.Combine(fullPath, "ModSettings");
        string str = System.IO.Path.Combine(PlatformFileHelperPCExtended.GetDirectoryFullPath(EngineFilePaths.ConfigsPath) ?? string.Empty, "ModSettings");
        if (!Directory.Exists(path) || !Directory.Exists(str))
          return;
        foreach (string file in Directory.GetFiles(path))
        {
          string fileName = System.IO.Path.GetFileName(file);
          string destFileName = System.IO.Path.Combine(str, fileName);
          try
          {
            File.Copy(file, destFileName, true);
            File.Delete(file);
          }
          catch (Exception ex)
          {
          }
        }
        foreach (string directory in Directory.GetDirectories(path))
        {
          string fileName = System.IO.Path.GetFileName(directory);
          string target = System.IO.Path.Combine(str, fileName);
          try
          {
            MoveDirectory(directory, target);
          }
          catch (Exception ex)
          {
          }
        }
        string[] files1 = Directory.GetFiles(path);
        int num1;
        if (files1 != null && files1.Length == 0)
        {
          string[] directories = Directory.GetDirectories(path);
          num1 = directories == null ? 0 : (directories.Length == 0 ? 1 : 0);
        }
        else
          num1 = 0;
        if (num1 != 0)
          Directory.Delete(path, true);
        string[] files2 = Directory.GetFiles(fullPath);
        int num2;
        if (files2 != null && files2.Length == 0)
        {
          string[] directories = Directory.GetDirectories(fullPath);
          num2 = directories == null ? 0 : (directories.Length == 0 ? 1 : 0);
        }
        else
          num2 = 0;
        if (num2 != 0)
          Directory.Delete(fullPath, true);
      }
      catch (Exception ex)
      {
      }

      static void MoveDirectory(string source, string target)
      {
        string str1 = source.TrimEnd('\\', ' ');
        string newValue = target.TrimEnd('\\', ' ');
        // ISSUE: reference to a compiler-generated field
        // ISSUE: reference to a compiler-generated field
        foreach (IGrouping<string, string> grouping in Directory.EnumerateFiles(str1, "*", SearchOption.AllDirectories).GroupBy<string, string>(MCMImplementationSubModule.\u003C\u003EO.\u003C0\u003E__GetDirectoryName ?? (MCMImplementationSubModule.\u003C\u003EO.\u003C0\u003E__GetDirectoryName = new Func<string, string>(System.IO.Path.GetDirectoryName))))
        {
          string str2 = grouping.Key.Replace(str1, newValue);
          Directory.CreateDirectory(str2);
          foreach (string str3 in (IEnumerable<string>) grouping)
          {
            string str4 = System.IO.Path.Combine(str2, System.IO.Path.GetFileName(str3));
            if (File.Exists(str4))
              File.Delete(str4);
            File.Move(str3, str4);
          }
        }
        Directory.Delete(source, true);
      }
    }

    private static void PerformMigration002()
    {
      try
      {
        string fullPath1 = System.IO.Path.GetFullPath("Configs");
        string fullPath2 = System.IO.Path.GetFullPath(System.IO.Path.Combine(PlatformFileHelperPCExtended.GetDirectoryFullPath(EngineFilePaths.ConfigsPath) ?? string.Empty, "../", "ModSettings"));
        string str = System.IO.Path.Combine(PlatformFileHelperPCExtended.GetDirectoryFullPath(EngineFilePaths.ConfigsPath) ?? string.Empty, "ModSettings");
        if (!Directory.Exists(fullPath2) || !Directory.Exists(str))
          return;
        foreach (string file in Directory.GetFiles(fullPath2))
        {
          string fileName = System.IO.Path.GetFileName(file);
          string destFileName = System.IO.Path.Combine(str, fileName);
          try
          {
            File.Copy(file, destFileName, true);
            File.Delete(file);
          }
          catch (Exception ex)
          {
          }
        }
        foreach (string directory in Directory.GetDirectories(fullPath2))
        {
          string fileName = System.IO.Path.GetFileName(directory);
          string target = System.IO.Path.Combine(str, fileName);
          try
          {
            MoveDirectory(directory, target);
          }
          catch (Exception ex)
          {
          }
        }
        string[] files1 = Directory.GetFiles(fullPath2);
        int num1;
        if (files1 != null && files1.Length == 0)
        {
          string[] directories = Directory.GetDirectories(fullPath2);
          num1 = directories == null ? 0 : (directories.Length == 0 ? 1 : 0);
        }
        else
          num1 = 0;
        if (num1 != 0)
          Directory.Delete(fullPath2, true);
        string[] files2 = Directory.GetFiles(fullPath1);
        int num2;
        if (files2 != null && files2.Length == 0)
        {
          string[] directories = Directory.GetDirectories(fullPath1);
          num2 = directories == null ? 0 : (directories.Length == 0 ? 1 : 0);
        }
        else
          num2 = 0;
        if (num2 != 0)
          Directory.Delete(fullPath1, true);
      }
      catch (Exception ex)
      {
      }

      static void MoveDirectory(string source, string target)
      {
        string str1 = source.TrimEnd('\\', ' ');
        string newValue = target.TrimEnd('\\', ' ');
        // ISSUE: reference to a compiler-generated field
        // ISSUE: reference to a compiler-generated field
        foreach (IGrouping<string, string> grouping in Directory.EnumerateFiles(str1, "*", SearchOption.AllDirectories).GroupBy<string, string>(MCMImplementationSubModule.\u003C\u003EO.\u003C0\u003E__GetDirectoryName ?? (MCMImplementationSubModule.\u003C\u003EO.\u003C0\u003E__GetDirectoryName = new Func<string, string>(System.IO.Path.GetDirectoryName))))
        {
          string str2 = grouping.Key.Replace(str1, newValue);
          Directory.CreateDirectory(str2);
          foreach (string str3 in (IEnumerable<string>) grouping)
          {
            string str4 = System.IO.Path.Combine(str2, System.IO.Path.GetFileName(str3));
            if (File.Exists(str4))
              File.Delete(str4);
            File.Move(str3, str4);
          }
        }
        Directory.Delete(source, true);
      }
    }
  }
}
